global with sharing class GenerateUtil{
    /**
     *  This class has the core functionality of the Application and most of the code gets executed against each User of the organization.  
     *  Object permissions are checked to confirm whether the user has enough permission to execute the code block. 
     *  Selective FLS checks are done on the custom fields as most of the code executes in batch process against each user.
     *   
     */
     
    public static String testVar = '';
    static Map<ID, ID> userMap1 = new Map<ID, ID>();
    static Map<ID, ID> userMap2 = new Map<ID, ID>();
    static Map<ID, ID> userMap3 = new Map<ID, ID>();
    static Map<ID, ID> userMap4 = new Map<ID, ID>();
    static Map<ID, ID> userMap5 = new Map<ID, ID>();
    Webservice static void getUserMap()
    {
	    Reporting_Manager__c[] rmList = [select Reporting_Manager__c from Reporting_Manager__c limit 1];
	    String fieldName = null;
	    if(rmList.size() > 0)
	    	fieldName = rmList[0].Reporting_Manager__c;
    	else
    		fieldName = 'ManagerId';
    	
    	if(fieldName == null)
    		fieldName = 'ManagerId';
    		
    	SOBject sobj = new User();
        for(User[] users: Database.query('Select Id, '+fieldName+' from User where IsActive = true'))
        {
            for(User u: users)
            {
            	sObj = u;
                if(userMap1.size()<1000)
                    userMap1.put(u.id, (ID)sObj.get(fieldName));
                else if(userMap2.size()<1000)
                    userMap2.put(u.id, (ID)sObj.get(fieldName));
                else if(userMap3.size()<1000)
                    userMap3.put(u.id, (ID)sObj.get(fieldName));
                else if(userMap4.size()<1000)
                    userMap4.put(u.id, (ID)sObj.get(fieldName));
                else if(userMap5.size()<1000)
                    userMap5.put(u.id, (ID)sObj.get(fieldName));
            }
        }
    }
    
    public static ID getUsersManagerIDFromMap(ID uID)
    {
    	if(userMap1.get(uID) != null)
    		return userMap1.get(uID);
    	else if(userMap2.get(uID) != null)
    		return userMap2.get(uID);
    	else if(userMap3.get(uID) != null)
    		return userMap3.get(uID);
    	else if(userMap4.get(uID) != null)
    		return userMap4.get(uID);
    	else if(userMap5.get(uID) != null)
    		return userMap5.get(uID);
    	else
    	{
		    Reporting_Manager__c[] rmList = [select Reporting_Manager__c from Reporting_Manager__c limit 1];
		    String fieldName = null;
		    if(rmList.size() > 0)
		    	fieldName = rmList[0].Reporting_Manager__c;
	    	else
	    		fieldName = 'ManagerId';

	    	if(fieldName == null)
	    		fieldName = 'ManagerId';
	    		
	    	SOBject sobj = new User();
    		User[] users = Database.query('Select Id, '+fieldName+' from User where id = :uId and IsActive = true');
    		if(users.size() > 0)
    		{
    			sObj = users[0];
    			return (ID)sObj.get(fieldName);
    		}
    	}
    	return null;
    }
    
    //This method executes is part of Batch process and the User who has the create permission on the Plan Document object and create, update permission on Batch object.
    Webservice static String generateContract2(String templateId, String requiredDate,String datasource, String attachmentId, String effectiveStartDate, String effectiveEndDate)
    {
        SObject scObj = new Sales_Contract__c();
        SObject bObj = new Batch__c();
        DataAccessControlUtil dacu = new DataAccessControlUtil();
        String BATCHID = '';

        String str = 'hello';
        String check = 'false';
        Integer totalDataSources = 0;
        Integer planDocsCreated = 0;
        List<Sales_Contract__c> planDocumentsList = new List<Sales_Contract__c>();
        Map<ID, Template_Role__c> tempRoleMap = new Map<ID, Template_Role__c>();
        Template_Role__c[] tempRoles = new List<Template_Role__c>();
        Approvers__c[] approver = null;
        
        if(dacu.isCreateableObjectByUser(scObj) == 'success' && dacu.isCreateableObjectByUser(bObj) == 'success' && dacu.isUpdateableObjectByUser(bObj) == 'success')
        {       
            try
            {
                try
                {
                	getUserMap();
                    //Get the Approvers assigned for this Template before generation of Plan Documents.
                    String[] approverExpectedFields = new String[]{'Template__c','Final_Approver__c','Final_Approver_Date__c','Level1__c','Level2__c','Level3__c','Level4__c','Level5__c','Level6__c','Level7__c','Level8__c','Level9__c','Level10__c','Level11__c','Level12__c','Level13__c','Level14__c','Level15__c','Level1_Due_Date__c','Level2_Due_Date__c','Level3_Due_Date__c','Level4_Due_Date__c','Level5_Due_Date__c','Level6_Due_Date__c','Level7_Due_Date__c','Level8_Due_Date__c','Level9_Due_Date__c','Level10_Due_Date__c','Level11_Due_Date__c','Level12_Due_Date__c','Level13_Due_Date__c','Level14_Due_Date__c','Level15_Due_Date__c'};
                    SObject appObj = new Approvers__c();
                    Map<String, Schema.SObjectField> approverFieldMap = dacu.getFieldMap(appObj);
                    Set<String> allowedROFields = dacu.getAccessibleFields(appObj, approverFieldMap, approverExpectedFields);
                    String formSoql = '';
                    Remote_IP_Address__c[] ripList = [select Is_Global_Approvers_Used__c,Plan_Document_Name__c from Remote_IP_Address__c];
                    if(!allowedROFields.isEmpty())
                    {
                        formSoql = 'Select ';
                        for(String roField: allowedROFields)
                        {
                            formSoql += roField+', ';
                        }
                        formSoql = formSoql.substring(0, formSoql.length() - 2);
                        
                        //Not filtering using the ownerId as the records are used by all Admins. 
                        formSoql += ' from Approvers__c ';
                        
                        //get Accessible fields for the Where clause filter
                        approverExpectedFields = new String[]{'Template__c'};
                        allowedROFields = dacu.getAccessibleFields(appObj, approverFieldMap, approverExpectedFields);
                        if(!allowedROFields.isEmpty())
                        {
                            formSoql += ' where ';
                            for(String roField: allowedROFields)
                            {
		                    	if(ripList.size() > 0 && ripList[0].Is_Global_Approvers_Used__c == false)
	                                formSoql += roField+' = :templateId order by CreatedDate desc limit 1 ';
		                        else
		                        	formSoql += roField+' = null order by CreatedDate desc limit 1 ';
                            }
                            
                        }
                        approver = Database.query(formSoql);
                    }        
                    
    
                    //Get the Roles associated with the Template.
                    for(Template_Role__c[] templateRoles : [SELECT Role_ID__c, User_Title__c FROM Template_Role__c tempRoles where tempRoles.Template_ID__c= :templateId])
                    {
                        for(Template_Role__c tr: templateRoles)
                        {
                            tempRoleMap.put(tr.Role_ID__c, tr);
                            tempRoles.add(tr);
                        }
                    }
                    if(tempRoles.size() == 0)
                    {
                        return 'No Roles associated with this Template.';
                    }
    
                    URL__c[] url = [SELECT Id, Url_Value__c FROM URL__c];

                    // Get the titles associated with the Template.
                    Template__c[] template = [SELECT Id, Name, EligibilityType__c FROM Template__c tc where tc.Id = :templateId ];
                                  
                    Batch__c  batch=null;
                    CallidusDataSource__c[] dsc=null;
                    Sales_Contract__c[] contracts= null;
    
                    Date dt = Date.today();
        
                    Template__c[] templateName = [SELECT Id, Name  FROM Template__c t where t.Id= :templateId];
                    TemplateDataMap__c[]  tempDataMap = [SELECT Id, Name, TemplateName__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c,Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c FROM TemplateDataMap__c tmap where tmap.TemplateName__c = :templateName[0].Name];
      
                    batch = new Batch__c();
                    batch.StartTime__c=datetime.now();
                    batch.TotalContracts__c = totalDataSources ;
                    batch.RemainingContracts__c = totalDataSources ;
                    batch.Status__c='InProgress';
                    if(effectiveStartDate.length() > 7 && effectiveStartDate.length() <= 10)
                    {
                        batch.Effective_Start_Date__c = Date.valueOf(effectiveStartDate);
                    }
                    
                    if(effectiveEndDate.length() > 7 && effectiveEndDate.length() <= 10)
                    {
                        batch.Effective_End_Date__c = Date.valueOf(effectiveEndDate);
                    }
                    
                    batch.TemplateId__c= templateId;
                    try
                    {
                        insert batch;
                    }
                    catch(DmlException e)
                    {
                        return e.getMessage()+' Errrror';
                    }
                    
                    BATCHID = batch.Id;
                    String syncDate = '';
                    if(template[0].EligibilityType__c=='Title')
                    {
                        if(testVar != '')
                        {
                            tempDataMap[0] = new TemplateDataMap__c();
                        }
                        return  defineEligibility2(attachmentId, templateId, requiredDate, datasource, tempRoles, planDocumentsList, tempDataMap, BATCHID, '2008-08-08', '2008-08-09');
                    }
                                 
                    for(CallidusDataSource__c[] src : [SELECT Name,FirstName__c,LastName__c,PayeeID__c,SyncDate__c,IsActive__c, UserID__c,UserRoleId__c,UserRoleName__c,User_Title__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c, Name31__c, Name32__c, Name33__c, Name34__c, Name35__c, Name36__c, Name37__c, Name38__c, Name39__c, Name40__c, Name41__c, Name42__c, Name43__c, Name44__c, Name45__c, Name46__c, Name47__c, Name48__c, Name49__c, Name50__c, Name51__c, Name52__c, Name53__c, Name54__c,Name55__c,Name56__c,Name57__c,Name58__c,Name59__c,Name60__c,Name61__c,Name62__c,Name63__c,Name64__c,Name65__c,Name66__c,Name67__c,Name68__c,Name69__c,Name70__c,Name71__c,Name72__c,Name73__c,Name74__c,Name75__c,Name76__c,Name77__c,Name78__c,Name79__c,Name80__c,Name81__c,Name82__c,Name83__c,Name84__c,Name85__c,Name86__c,Name87__c,Name88__c,Name89__c,Name90__c,Value31__c, Value32__c, Value33__c, Value34__c, Value35__c, Value36__c, Value37__c, Value38__c, Value39__c, Value40__c, Value41__c, Value42__c, Value43__c, Value44__c, Value45__c, Value46__c, Value47__c, Value48__c, Value49__c, Value50__c, Value51__c, Value52__c, Value53__c, Value54__c,Value55__c,Value56__c,Value57__c,Value58__c,Value59__c,Value60__c,Value61__c,Value62__c,Value63__c,Value64__c,Value65__c,Value66__c,Value67__c,Value68__c,Value69__c,Value70__c,Value71__c,Value72__c,Value73__c,Value74__c,Value75__c,Value76__c,Value77__c,Value78__c,Value79__c,Value80__c,Value81__c,Value82__c,Value83__c,Value84__c,Value85__c,Value86__c,Value87__c,Value88__c,Value89__c,Value90__c FROM CallidusDataSource__c dsc where dsc.UserRoleId__c in : tempRoleMap.keyset() and dsc.IsActive__c = true])
                    {
                        contracts = new Sales_Contract__c[src.size()];
                        totalDataSources += src.size();
                        Integer i = 0;
                        for(CallidusDataSource__c sources : src)
                        {
                            syncDate = sources.SyncDate__c;
                            if(sources.PayeeID__c == null && dataSource == 'True Comp')
                            {
                                i++;
                                continue;
                            }
                              
                            check = 'true';  
                
                            contracts[i] = new Sales_Contract__c();
                            contracts[i].FirstName__c =sources.FirstName__c;
                            contracts[i].Generated_Date__c = dt;
                            contracts[i].LastName__c =sources.LastName__c;
                            contracts[i].Status__c = 'Draft';
                            contracts[i].UserID__c = sources.UserID__c;
                            contracts[i].User_ID__c = sources.UserID__c;
                            contracts[i].UserRoleId__c = sources.UserRoleId__c;
                            contracts[i].User_Title__c = sources.User_Title__c;
                            contracts[i].PayeeID__c =sources.PayeeID__c;
                            contracts[i].UserRoleName__c = sources.UserRoleName__c;
                            contracts[i].TemplateName__c = templateName[0].Name;
                            contracts[i].Template__c = templateName[0].Id;
                            contracts[i].BatchID__c = batch.Id;
				            contracts[i].is_merge_document__c = true;
                            contracts[i].Batch__c = batch.Id;
				            if(ripList.size() > 0 && ripList[0].Plan_Document_Name__c != null)
				                contracts[i].Plan_Document_Name__c = ripList[0].Plan_Document_Name__c+' '+sources.FirstName__c+' '+sources.LastName__c+' '+dt.month()+'/'+dt.day()+'/'+dt.year();
                            else
                                contracts[i].Plan_Document_Name__c = templateName[0].Name+' '+sources.FirstName__c+' '+sources.LastName__c+' 0'+dt.month()+'/'+dt.day()+'/'+dt.year();
                            
                            if(approver.size() > 0)
                            {
                                if(testVar != '' && testVar.length() > 0)
                                {
                                    approver[0].Level1__c = Userinfo.getUserId();
                                    approver[0].Final_Approver__c = Userinfo.getUserId();
                                    approver[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                                }
                                                
                                contracts[i] = populateSalesContractLevels(contracts[i], approver[0], sources.UserID__c);
                                system.debug('SalesContract Level1 is :::::: '+contracts[i].Level1__c);
                            }
                                
                            if(url.size() > 0)
                            {
                                contracts[i].Url__c = url[0].Url_Value__c;
                            }

                            if(effectiveStartDate.length() > 7 && effectiveStartDate.length() <= 10)
                            {
                                contracts[i].Effective_Start_Date__c = Date.valueOf(effectiveStartDate);
                            }
                            
                            if(effectiveEndDate.length() > 7 && effectiveEndDate.length() <= 10)
                            {
                                contracts[i].Effective_End_Date__c = Date.valueOf(effectiveEndDate);
                            }
                            
                            if(requiredDate.length() > 7 && requiredDate.length() <= 10)
                            {
                                contracts[i].RequiredReturnDate__c = Date.valueOf(requiredDate);
                            }
                            
                            if(datasource!='True Comp')
                            {
                                contracts[i] = populateNameValuePairs(contracts[i], sources);
                            }
                            else
                            {
                                if(tempDataMap.size() > 0)
                                {   
                                    contracts[i] = populateFromTemplateDataMap(contracts[i], tempDataMap[0]);
                                }
                        
                            }
                            
                            contracts[i].AttachmentID__c = attachmentId;
                            planDocumentsList.add(contracts[i]);
                            i++;
                            planDocsCreated++;
                            if(planDocumentsList.size() == 200 || i == src.size())
                            {
                                try
                                {
                                    insert planDocumentsList;
                                }
                                catch(DmlException d)
                                {   
                                    return 'While inserting Contracts   '+d+'   ';
                                }
                                Integer j=0;
                                String ids = '';
                                planDocumentsList.clear();
    
                            }//end of if(planDocumentsList.size() == 199) 
                            
                        }//end of for(CallidusDataSource__c sources : src)

                    }//end of for(CallidusDataSource__c[] sources:[SELECT Name,FirstName__c,LastName__c,PayeeID__c,SyncDate__c,UserID__c,UserRoleId__c,UserRoleName__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c FROM CallidusDataSource__c dsc where dsc.UserRoleId__c in :tempRoleMap.keyset()])
                
                    Batch__c[] btch = [SELECT Status__c, TotalContracts__c, RemainingContracts__c, EndTime__c,Datasource__c from Batch__c b where  b.Id = :batch.Id];
    
                    btch[0].RemainingContracts__c = totalDataSources - planDocsCreated;
                    btch[0].TotalContracts__c = planDocsCreated;
                    btch[0].EndTime__c = datetime.now();
                    if(syncDate != null && syncDate != '')
                    {
                        btch[0].specifydate__c = Date.valueOf(syncDate);
                    }
                    btch[0].Datasource__c = datasource;
                    btch[0].Status__c = 'Completed';
                    try
                    {
                        update btch;
                    }
                    catch(DmlException e) 
                    {   
                        return e.getMessage();
                    }  
          
                }
                catch(Exception e)
                {
                    
                    return e.getMessage();
                }
        
                if(check == 'true')
                    return BATCHID;
                else
                    return 'false';
            }
            catch(Exception e)
            {
                return e.getMessage();
            }   
            
        }
        
        return 'success';       
    }
    
    public static Sales_Contract__c populateNameValuePairs(Sales_Contract__c contracts, CallidusDataSource__c sources)
    {
        contracts.Name1__c = sources.Name1__c;
        contracts.Name2__c = sources.Name2__c;
        contracts.Name3__c = sources.Name3__c;   
        contracts.Name4__c = sources.Name4__c;
        contracts.Name5__c = sources.Name5__c;
        contracts.Name6__c = sources.Name6__c;     
        contracts.Name7__c = sources.Name7__c;
        contracts.Name8__c = sources.Name8__c;
        contracts.Name9__c = sources.Name9__c;   
        contracts.Name10__c = sources.Name10__c;
        contracts.Name11__c = sources.Name11__c;
        contracts.Name12__c = sources.Name12__c;     
        contracts.Name13__c = sources.Name13__c;
        contracts.Name14__c = sources.Name14__c;
        contracts.Name15__c = sources.Name15__c;   
        contracts.Name16__c = sources.Name16__c;
        contracts.Name17__c = sources.Name17__c;
        contracts.Name18__c = sources.Name18__c;     
        contracts.Name19__c = sources.Name19__c;
        contracts.Name20__c = sources.Name20__c;
        contracts.Name21__c = sources.Name21__c;   
        contracts.Name22__c = sources.Name22__c;
        contracts.Name23__c = sources.Name23__c;
        contracts.Name24__c = sources.Name24__c;     
        contracts.Name25__c = sources.Name25__c;
        contracts.Name26__c = sources.Name26__c;
        contracts.Name27__c = sources.Name27__c;   
        contracts.Name28__c = sources.Name28__c;
        contracts.Name29__c = sources.Name29__c;
        contracts.Name30__c = sources.Name30__c;     
        contracts.Name31__c = sources.Name31__c;
        contracts.Name32__c = sources.Name32__c;
        contracts.Name33__c = sources.Name33__c;   
        contracts.Name34__c = sources.Name34__c;
        contracts.Name35__c = sources.Name35__c;
        contracts.Name36__c = sources.Name36__c;     
        contracts.Name37__c = sources.Name37__c;
        contracts.Name38__c = sources.Name38__c;
        contracts.Name39__c = sources.Name39__c;   
        contracts.Name40__c = sources.Name40__c;
        contracts.Name41__c = sources.Name41__c;
        contracts.Name42__c = sources.Name42__c;     
        contracts.Name43__c = sources.Name43__c;
        contracts.Name44__c = sources.Name44__c;
        contracts.Name45__c = sources.Name45__c;   
        contracts.Name46__c = sources.Name46__c;
        contracts.Name47__c = sources.Name47__c;
        contracts.Name48__c = sources.Name48__c;     
        contracts.Name49__c = sources.Name49__c;
        contracts.Name50__c = sources.Name50__c;
        contracts.Name51__c = sources.Name51__c;   
        contracts.Name52__c = sources.Name52__c;
        contracts.Name53__c = sources.Name53__c;
        contracts.Name54__c = sources.Name54__c;     
        contracts.Name55__c = sources.Name55__c;     
        contracts.Name56__c = sources.Name56__c;     
        contracts.Name57__c = sources.Name57__c;     
        contracts.Name58__c = sources.Name58__c;     
        contracts.Name59__c = sources.Name59__c;     
        contracts.Name60__c = sources.Name60__c;     
        contracts.Name61__c = sources.Name61__c;     
        contracts.Name62__c = sources.Name62__c;     
        contracts.Name63__c = sources.Name63__c;     
        contracts.Name64__c = sources.Name64__c;     
        contracts.Name65__c = sources.Name65__c;     
        contracts.Name66__c = sources.Name66__c;     
        contracts.Name67__c = sources.Name67__c;     
        contracts.Name68__c = sources.Name68__c;     
        contracts.Name69__c = sources.Name69__c;     
        contracts.Name70__c = sources.Name70__c;     
        contracts.Name71__c = sources.Name71__c;     
        contracts.Name72__c = sources.Name72__c;     
        contracts.Name73__c = sources.Name73__c;     
        contracts.Name74__c = sources.Name74__c;     
        contracts.Name75__c = sources.Name75__c;     
        contracts.Name76__c = sources.Name76__c;     
        contracts.Name77__c = sources.Name77__c;     
        contracts.Name78__c = sources.Name78__c;     
        contracts.Name79__c = sources.Name79__c;     
        contracts.Name80__c = sources.Name80__c;     
        contracts.Name81__c = sources.Name81__c;     
        contracts.Name82__c = sources.Name82__c;     
        contracts.Name83__c = sources.Name83__c;     
        contracts.Name84__c = sources.Name84__c;     
        contracts.Name85__c = sources.Name85__c;     
        contracts.Name86__c = sources.Name86__c;     
        contracts.Name87__c = sources.Name87__c;     
        contracts.Name88__c = sources.Name88__c;     
        contracts.Name89__c = sources.Name89__c;     
        contracts.Name90__c = sources.Name90__c;     
        
        contracts.Value1__c = sources.Value1__c;
        contracts.Value2__c = sources.Value2__c;
        contracts.Value3__c = sources.Value3__c;
        contracts.Value4__c = sources.Value4__c;
        contracts.Value5__c = sources.Value5__c;
        contracts.Value6__c = sources.Value6__c;
        contracts.Value7__c = sources.Value7__c;
        contracts.Value8__c = sources.Value8__c;
        contracts.Value9__c = sources.Value9__c;
        contracts.Value10__c = sources.Value10__c;
        contracts.Value11__c = sources.Value11__c;
        contracts.Value12__c = sources.Value12__c;
        contracts.Value13__c = sources.Value13__c;
        contracts.Value14__c = sources.Value14__c;
        contracts.Value15__c = sources.Value15__c;
        contracts.Value16__c = sources.Value16__c;
        contracts.Value17__c = sources.Value17__c;
        contracts.Value18__c = sources.Value18__c;
        contracts.Value19__c = sources.Value19__c;
        contracts.Value20__c = sources.Value20__c;
        contracts.Value21__c = sources.Value21__c;
        contracts.Value22__c = sources.Value22__c;
        contracts.Value23__c = sources.Value23__c;
        contracts.Value24__c = sources.Value24__c;
        contracts.Value25__c = sources.Value25__c;
        contracts.Value26__c = sources.Value26__c;
        contracts.Value27__c = sources.Value27__c;
        contracts.Value28__c = sources.Value28__c;
        contracts.Value29__c = sources.Value29__c;
        contracts.Value30__c = sources.Value30__c;
        contracts.Value31__c = sources.Value31__c;
        contracts.Value32__c = sources.Value32__c;
        contracts.Value33__c = sources.Value33__c;
        contracts.Value34__c = sources.Value34__c;
        contracts.Value35__c = sources.Value35__c;
        contracts.Value36__c = sources.Value36__c;
        contracts.Value37__c = sources.Value37__c;
        contracts.Value38__c = sources.Value38__c;
        contracts.Value39__c = sources.Value39__c;
        contracts.Value40__c = sources.Value40__c;
        contracts.Value41__c = sources.Value41__c;
        contracts.Value42__c = sources.Value42__c;
        contracts.Value43__c = sources.Value43__c;
        contracts.Value44__c = sources.Value44__c;
        contracts.Value45__c = sources.Value45__c;
        contracts.Value46__c = sources.Value46__c;
        contracts.Value47__c = sources.Value47__c;
        contracts.Value48__c = sources.Value48__c;
        contracts.Value49__c = sources.Value49__c;
        contracts.Value50__c = sources.Value50__c;
        contracts.Value51__c = sources.Value51__c;
        contracts.Value52__c = sources.Value52__c;
        contracts.Value53__c = sources.Value53__c;
        contracts.Value54__c = sources.Value54__c;
        contracts.Value55__c = sources.Value55__c;     
        contracts.Value56__c = sources.Value56__c;     
        contracts.Value57__c = sources.Value57__c;     
        contracts.Value58__c = sources.Value58__c;     
        contracts.Value59__c = sources.Value59__c;     
        contracts.Value60__c = sources.Value60__c;     
        contracts.Value61__c = sources.Value61__c;     
        contracts.Value62__c = sources.Value62__c;     
        contracts.Value63__c = sources.Value63__c;     
        contracts.Value64__c = sources.Value64__c;     
        contracts.Value65__c = sources.Value65__c;     
        contracts.Value66__c = sources.Value66__c;     
        contracts.Value67__c = sources.Value67__c;     
        contracts.Value68__c = sources.Value68__c;     
        contracts.Value69__c = sources.Value69__c;     
        contracts.Value70__c = sources.Value70__c;     
        contracts.Value71__c = sources.Value71__c;     
        contracts.Value72__c = sources.Value72__c;     
        contracts.Value73__c = sources.Value73__c;     
        contracts.Value74__c = sources.Value74__c;     
        contracts.Value75__c = sources.Value75__c;     
        contracts.Value76__c = sources.Value76__c;     
        contracts.Value77__c = sources.Value77__c;     
        contracts.Value78__c = sources.Value78__c;     
        contracts.Value79__c = sources.Value79__c;     
        contracts.Value80__c = sources.Value80__c;     
        contracts.Value81__c = sources.Value81__c;     
        contracts.Value82__c = sources.Value82__c;     
        contracts.Value83__c = sources.Value83__c;     
        contracts.Value84__c = sources.Value84__c;     
        contracts.Value85__c = sources.Value85__c;     
        contracts.Value86__c = sources.Value86__c;     
        contracts.Value87__c = sources.Value87__c;     
        contracts.Value88__c = sources.Value88__c;     
        contracts.Value89__c = sources.Value89__c;     
        contracts.Value90__c = sources.Value90__c;     

        return contracts;       
    }

    public static Sales_Contract__c populateFromTemplateDataMap(Sales_Contract__c contracts, TemplateDataMap__c tempDataMap)
    {
        contracts.Name1__c = tempDataMap.Name1__c;
        contracts.Name2__c = tempDataMap.Name2__c;
        contracts.Name3__c = tempDataMap.Name3__c;   
        contracts.Name4__c = tempDataMap.Name4__c;
        contracts.Name5__c = tempDataMap.Name5__c;
        contracts.Name6__c = tempDataMap.Name6__c;     
        contracts.Name7__c = tempDataMap.Name7__c;
        contracts.Name8__c = tempDataMap.Name8__c;
        contracts.Name9__c = tempDataMap.Name9__c;   
        contracts.Name10__c = tempDataMap.Name10__c;
        contracts.Name11__c = tempDataMap.Name11__c;
        contracts.Name12__c = tempDataMap.Name12__c;     
        contracts.Name13__c = tempDataMap.Name13__c;
        contracts.Name14__c = tempDataMap.Name14__c;
        contracts.Name15__c = tempDataMap.Name15__c;   
        contracts.Name16__c = tempDataMap.Name16__c;
        contracts.Name17__c = tempDataMap.Name17__c;
        contracts.Name18__c = tempDataMap.Name18__c;     
        contracts.Name19__c = tempDataMap.Name19__c;
        contracts.Name20__c = tempDataMap.Name20__c;
        contracts.Name21__c = tempDataMap.Name21__c;   
        contracts.Name22__c = tempDataMap.Name22__c;
        contracts.Name23__c = tempDataMap.Name23__c;
        contracts.Name24__c = tempDataMap.Name24__c;     
        contracts.Name25__c = tempDataMap.Name25__c;
        contracts.Name26__c = tempDataMap.Name26__c;
        contracts.Name27__c = tempDataMap.Name27__c;   
        contracts.Name28__c = tempDataMap.Name28__c;
        contracts.Name29__c = tempDataMap.Name29__c;
        contracts.Name30__c = tempDataMap.Name30__c; 
        return contracts;
    }

    //This code will be executed for every user of the application. Users should have Update permission on Plan Document object for this code block to execute. 
    WebService static String updatePlanDocStatus2(String[] salesContractId, String batchId, String url, String requiredReturnDate, String templateId)
    {
        SObject scObj = new Sales_Contract__c();
        SObject bObj = new Batch__c();
        DataAccessControlUtil dacu = new DataAccessControlUtil();
        if(dacu.isUpdateableObjectByUser(scObj) == 'success' && dacu.isUpdateableObjectByUser(bObj) == 'success')
        {       
            //Get the Approvers assigned for this Template before generation of Plan Documents.
            Approvers__c[] approver = null;
                    
            String[] approverExpectedFields = new String[]{'Template__c'};
            SObject appObj = new Approvers__c();
            Map<String, Schema.SObjectField> approverFieldMap = dacu.getFieldMap(appObj);
            Set<String> allowedROFields = dacu.getAccessibleFields(appObj, approverFieldMap, approverExpectedFields);
            String formSoql = '';
            if(!allowedROFields.isEmpty())
            {
                formSoql = 'Select ';
                for(String roField: allowedROFields)
                {
                    formSoql += roField+', ';
                }
                formSoql = formSoql.substring(0, formSoql.length() - 2);
                
                //Not filtering using the ownerId as the records are used by all Admins. 
                formSoql += ' from Approvers__c ';
                
                //get Accessible fields for the Where clause filter
                approverExpectedFields = new String[]{'Template__c'};
                allowedROFields = dacu.getAccessibleFields(appObj, approverFieldMap, approverExpectedFields);
                Remote_IP_Address__c[] ripList = [select Is_Global_Approvers_Used__c from Remote_IP_Address__c];
                if(!allowedROFields.isEmpty())
                {
                    formSoql += ' where ';
                    for(String roField: allowedROFields)
                    {
                    	if(ripList.size() > 0 && ripList[0].Is_Global_Approvers_Used__c == false)
	                        formSoql += roField+' = :templateId order by CreatedDate desc limit 1 ';
                        else
                        	formSoql += roField+' = null order by CreatedDate desc limit 1 ';
                    }
                    
                }
                approver = Database.query(formSoql);
            }        
            if(approver.size() > 0)
            {
               try
               {
                   for(Integer k=0; k<salesContractId.size(); k++)
                   {
                       Sales_Contract__c[] sc = [SELECT Id, OwnerId, FirstName__c, LastName__c, Level1__c, Level1_Due_Date__c, Status__c, Name, UserID__c from Sales_Contract__c s where s.Id = :salesContractId[k]];
                       if(sc[0].Level1__c != null)
                       {
                           if(sc.size() == 0)
                           {
                               
                               return 'Sales Contract does not exist';
                           }
        
                           sc[0].Status__c = 'Distributed';
                        
                           Batch__c[] b = [Select Status__c from Batch__c b where b.Id = :batchId];
                           if(b.size() > 0)
                           {
                               b[0].Status__c = 'Distributed';
                               try
                               {
                                   update sc;
                                   update b;
                               }
                               catch(DmlException e)
                               {  
                                  return 'While Updating SalesContract and Batch  '+e;
                               }
                               Approval.ProcessSubmitRequest request =new Approval.ProcessSubmitRequest();
                               request.setObjectId(sc[0].Id);
                               Approval.ProcessResult result = Approval.process(request);
                    
                           }
                        
                           Task t = new Task();
                           t.OwnerId = sc[0].Level1__c;
                           t.WhatId = sc[0].Id;
                           t.Subject = 'Plan Document Distributed';
                           t.Description = 'Plan Document Distributed.';
                           t.Status = 'NotStarted';
                           t.Type = 'Email';
                           t.ActivityDate = sc[0].Level1_Due_Date__c;//Date.valueof(requiredReturnDate);
                           String remDateTime = sc[0].Level1_Due_Date__c+' 08:00:00';
                           t.ReminderDateTime = Datetime.valueof(remDateTime) - 3;
                           t.IsReminderSet = true;
                           t.Priority = 'Normal';
                        
                           try
                           {
                                insert t;
                           }
                           catch(DmlException d)
                           { 
                             
                             return ' '+d;
                           }
                           Sales_Contract__History history = new Sales_Contract__History(ParentId = salesContractId[k]);
            
                        }
                    }
                }
                catch(Exception e)
                {
                    return 'List has no rows  '+e.getMessage();
                }
            }
            else
            {
               try
               {
                   String subject;
                   String textBody;
                   String htmlBody;
                   String str;
                
                   for(Integer k=0; k<salesContractId.size(); k++)
                   {
                       Sales_Contract__c[] sc = [SELECT Id, OwnerId, Status__c, Name, Firstname__c, UserID__c, RequiredReturnDate__c from Sales_Contract__c s where s.Id = :salesContractId[k]];
                    
                       if(sc.size() == 0)
                       {
                           return 'Sales Contract does not exist';
                       }
        
                       sc[0].Status__c = 'Published';
                       
        
                       Batch__c[] b = [Select Status__c from Batch__c b where b.Id = :batchId];
                       if(b.size() > 0)
                       {
                           b[0].Status__c = 'Distributed';
                           update sc;
                           update b;
                       }
                       
                    }
                }
                catch(Exception e)
                {
                	system.debug('Error :::: '+e.getMessage());
                    return 'List has no rows  '+e.getMessage();
                }
                
            }
        }
        return 'success';
    }

    //This method gets invoked from the generateContracts2 method.  
    public static Sales_Contract__c populateSalesContractLevels(Sales_Contract__c sc, Approvers__c approver, String userId)
    {
        Schema.DescribeSobjectResult dsr = User.sObjectType.getDescribe();
        if(dsr.isAccessible())
        {      
            if(approver.Level1__c != null)
            {
                sc.Level1__c = getUsersManagerIDFromMap(userId);
                sc.Level1_Due_Date__c = approver.Level1_Due_Date__c;
            }
            if(approver.Level2__c != null)
            {
                sc.Level2__c = getUsersManagerIDFromMap(sc.Level1__c);
                sc.Level2_Due_Date__c = approver.Level2_Due_Date__c;
            }
            if(approver.Level3__c != null)
            {
                sc.Level3__c = getUsersManagerIDFromMap(sc.Level2__c);
                sc.Level3_Due_Date__c = approver.Level3_Due_Date__c;
            }
            if(approver.Level4__c != null)
            {
                sc.Level4__c = getUsersManagerIDFromMap(sc.Level3__c);
                sc.Level4_Due_Date__c = approver.Level4_Due_Date__c;
            }
            if(approver.Level5__c != null)
            {
                sc.Level5__c = getUsersManagerIDFromMap(sc.Level4__c);
                sc.Level5_Due_Date__c = approver.Level5_Due_Date__c;
            }
            if(approver.Level6__c != null)
            {
                sc.Level6__c = getUsersManagerIDFromMap(sc.Level5__c);
                sc.Level6_Due_Date__c = approver.Level6_Due_Date__c;
            }
            if(approver.Level7__c != null)
            {
                sc.Level7__c = getUsersManagerIDFromMap(sc.Level6__c);
                sc.Level7_Due_Date__c = approver.Level7_Due_Date__c;
            }

            if(approver.Final_Approver__c != null)
            {
                sc.Final_Approver__c = approver.Final_Approver__c;
                sc.Final_Approver_Date__c = approver.Final_Approver_Date__c;
            }
        }
        return sc;
    }//end of public static populateSalesContractLevels()

    WebService static String updateTemplateStatus(String templateId)
    {  
        Schema.DescribeSobjectResult dsr = Template__c.sObjectType.getDescribe();
        Schema.DescribeFieldResult dfrId = Template__c.Id.getDescribe();
        Schema.DescribeFieldResult dfrStatus = Template__c.Status__c.getDescribe();
        if(dsr.isAccessible() && dsr.isUpdateable() && dfrId.isAccessible() && dfrStatus.isAccessible())
        {       
           Template__c[] tmp = [SELECT Status__c from Template__c t where t.Id = :templateId];
           if(tmp.size() > 0)
           {
               tmp[0].Status__c = 'In Use';
               try
               {
                   update tmp;
               }
               catch(DmlException e)
               {
                   return e.getMessage();
               }
            }
        }
        return 'success';
    }
    
    WebService static String sendMailToUser(String userId, String subject, String textBody, String htmlBody)
    {
        Schema.DescribeSobjectResult dsr = User.sObjectType.getDescribe();
        if(dsr.isAccessible())
        {      
            User[] u = [Select FirstName, Email from User us where us.Id = :userId];
            if(u.size() == 0)
            {
                return 'No User exists';
            }
            String firstName = u[0].FirstName;
            
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
            // Strings to hold the email addresses to which you are sending the email.
            String[] toAddresses = new String[] {u[0].Email}; 
            String[] ccAddresses = new String[] {};
          
        
            // Assign the addresses for the To and CC lists to the mail object.
            mail.setToAddresses(toAddresses);
            mail.setCcAddresses(ccAddresses);
        
            // Specify the name used as the display name.
            mail.setSenderDisplayName(UserInfo.getName());
        
            // Specify the subject line for your email address.
            mail.setSubject(''+subject+'');
        
            // Set to True if you want to BCC yourself on the email.
            mail.setBccSender(false);
            
            // Optionally append the salesforce.com email signature to the email.
            // The email address of the user executing the Apex Code will be used.
            mail.setUseSignature(false);
            
            // Specify the text content of the email.
            mail.setPlainTextBody(''+textBody+'');
        
            mail.setHtmlBody('Dear <b>'+firstName+'</b>,<br/><br/>'+htmlBody+'');
        
            // Send the email you have created.
            Messaging.SendEmailResult[] ser = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            if(ser.size() > 0 && ser[0].getErrors().size() > 0)
                return 'success = '+ser[0].isSuccess()+'  = '+(ser[0].getErrors())[0].getMessage();
            else 
                return 'success';
        }       
        return 'failure';
    }//end of method sendMailToUser

    Webservice static String generateContract(String templateId, String requiredDate,String datasource)
    {
        return 'success';
    }

    WebService static String defineEligibility(Attachment[] templateAttachment,String templateId, String requiredDate,String datasource,Template_Role__c[] tempTitles,List<Sales_Contract__c> planDocumentsList,TemplateDataMap__c[]  tempDataMap,String BATCHID)
    {
        return 'success';
    }

    //This code is common to all the users in the organization
    WebService static String updateStatus(String salesContractName)
    {  
        return 'success';
    }
    
    //This code is common to all the Users of the organization 
    WebService static String defineEligibility2(String attachmentId,String templateId, String requiredDate,String datasource,Template_Role__c[] tempTitles,List<Sales_Contract__c> planDocumentsList,TemplateDataMap__c[]  tempDataMap, String BATCHID, String effectiveStartDate, String effectiveEndDate)
    {
        SObject scObj = new Sales_Contract__c();
        SObject bObj = new Batch__c();
        DataAccessControlUtil dacu = new DataAccessControlUtil();
        if(dacu.isCreateableObjectByUser(scObj) == 'success' && dacu.isCreateableObjectByUser(bObj) == 'success')
        {       
            CallidusDataSource__c[] dsc=null;
            Sales_Contract__c[] contracts= null;
            String check = 'false';
            Integer totalDataSources = 0;
            Integer planDocsCreated = 0;
            String syncDate = '';
            Date dt = Date.today();
            
            Template__c[] templateName = [SELECT Id, Name  FROM Template__c t where t.Id= :templateId];
            //Get the Approvers assigned for this Template before generation of Plan Documents.
            Approvers__c[] approver = null;
            Remote_IP_Address__c[] ripList = [select Is_Global_Approvers_Used__c, Plan_Document_Name__c from Remote_IP_Address__c];
                    
            String[] approverExpectedFields = new String[]{'Template__c','Final_Approver__c','Final_Approver_Date__c','Level1__c','Level2__c','Level3__c','Level4__c','Level5__c','Level6__c','Level7__c','Level8__c','Level9__c','Level10__c','Level11__c','Level12__c','Level13__c','Level14__c','Level15__c','Level1_Due_Date__c','Level2_Due_Date__c','Level3_Due_Date__c','Level4_Due_Date__c','Level5_Due_Date__c','Level6_Due_Date__c','Level7_Due_Date__c','Level8_Due_Date__c','Level9_Due_Date__c','Level10_Due_Date__c','Level11_Due_Date__c','Level12_Due_Date__c','Level13_Due_Date__c','Level14_Due_Date__c','Level15_Due_Date__c'};
            SObject appObj = new Approvers__c();
            Map<String, Schema.SObjectField> approverFieldMap = dacu.getFieldMap(appObj);
            Set<String> allowedROFields = dacu.getAccessibleFields(appObj, approverFieldMap, approverExpectedFields);
            String formSoql = '';
            if(!allowedROFields.isEmpty())
            {
                formSoql = 'Select ';
                for(String roField: allowedROFields)
                {
                    formSoql += roField+', ';
                }
                formSoql = formSoql.substring(0, formSoql.length() - 2);
                
                //Not filtering using the ownerId as the records are used by all Admins. 
                formSoql += ' from Approvers__c ';
                
                //get Accessible fields for the Where clause filter
                approverExpectedFields = new String[]{'Template__c'};
                allowedROFields = dacu.getAccessibleFields(appObj, approverFieldMap, approverExpectedFields);
                if(!allowedROFields.isEmpty())
                {
                    formSoql += ' where ';
                    for(String roField: allowedROFields)
                    {
                    	if(ripList.size() > 0 && ripList[0].Is_Global_Approvers_Used__c == false)
                        	formSoql += roField+' = :templateId order by CreatedDate desc limit 1 ';
                        else
                        	formSoql += roField+' = null order by CreatedDate desc limit 1 ';
                    }
                }
                approver = Database.query(formSoql);
            }        
        
            URL__c[] url = [SELECT Id, Url_Value__c FROM URL__c];
            Map<String, Template_Role__c> tempRoleMap = new Map<String, Template_Role__c>();
    
            for(Template_Role__c tr: tempTitles)
            {
                tempRoleMap.put(tr.User_Title__c, tr);
            }
    
            try
            {    
                for(CallidusDataSource__c[] src : [SELECT Name, FirstName__c,LastName__c,PayeeID__c,SyncDate__c, IsActive__c, UserID__c,UserRoleId__c,UserRoleName__c,User_Title__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c, Name31__c, Name32__c, Name33__c, Name34__c, Name35__c, Name36__c, Name37__c, Name38__c, Name39__c, Name40__c, Name41__c, Name42__c, Name43__c, Name44__c, Name45__c, Name46__c, Name47__c, Name48__c, Name49__c, Name50__c, Name51__c, Name52__c, Name53__c, Name54__c,Name55__c,Name56__c,Name57__c,Name58__c,Name59__c,Name60__c,Name61__c,Name62__c,Name63__c,Name64__c,Name65__c,Name66__c,Name67__c,Name68__c,Name69__c,Name70__c,Name71__c,Name72__c,Name73__c,Name74__c,Name75__c,Name76__c,Name77__c,Name78__c,Name79__c,Name80__c,Name81__c,Name82__c,Name83__c,Name84__c,Name85__c,Name86__c,Name87__c,Name88__c,Name89__c,Name90__c,Value31__c, Value32__c, Value33__c, Value34__c, Value35__c, Value36__c, Value37__c, Value38__c, Value39__c, Value40__c, Value41__c, Value42__c, Value43__c, Value44__c, Value45__c, Value46__c, Value47__c, Value48__c, Value49__c, Value50__c, Value51__c, Value52__c, Value53__c, Value54__c,Value55__c,Value56__c,Value57__c,Value58__c,Value59__c,Value60__c,Value61__c,Value62__c,Value63__c,Value64__c,Value65__c,Value66__c,Value67__c,Value68__c,Value69__c,Value70__c,Value71__c,Value72__c,Value73__c,Value74__c,Value75__c,Value76__c,Value77__c,Value78__c,Value79__c,Value80__c,Value81__c,Value82__c,Value83__c,Value84__c,Value85__c,Value86__c,Value87__c,Value88__c,Value89__c,Value90__c FROM CallidusDataSource__c dsc where dsc.User_Title__c in : tempRoleMap.keyset() and dsc.IsActive__c = true ])
                {
                    contracts = new Sales_Contract__c[src.size()];
                    totalDataSources += src.size();
                    Integer i = 0;
                    for(CallidusDataSource__c sources : src)
                    {
                        syncDate = sources.SyncDate__c;
                        if(sources.PayeeID__c == null && dataSource == 'True Comp')
                        {
                            i++;
                            continue;
                        }
                          
                        check = 'true';  
                
                        contracts[i] = new Sales_Contract__c();
                        contracts[i].FirstName__c=sources.FirstName__c;
                        contracts[i].Generated_Date__c= dt;
                        contracts[i].LastName__c=sources.LastName__c;
                        contracts[i].Status__c= 'Draft';
                        contracts[i].UserID__c= sources.UserID__c;
                        contracts[i].User_ID__c= sources.UserID__c;
                        contracts[i].UserRoleId__c=sources.UserRoleId__c;
                        contracts[i].User_Title__c=sources.User_Title__c;
                        contracts[i].PayeeID__c=sources.PayeeID__c;
                        contracts[i].UserRoleName__c= sources.UserRoleName__c;
                        contracts[i].TemplateName__c= templateName[0].Name;
                        contracts[i].Template__c = templateName[0].Id;
			            contracts[i].is_merge_document__c = true;
                        contracts[i].BatchID__c = BATCHID;
                        contracts[i].Batch__c = BATCHID;

                        if(url.size() > 0)
                        {
                            contracts[i].Url__c=url[0].Url_Value__c;
                        }
                        if(effectiveStartDate.length() > 7 && effectiveStartDate.length() <= 10)
                        {
                            contracts[i].Effective_Start_Date__c = Date.valueOf(effectiveStartDate);
                        }
                        
                        if(effectiveEndDate.length() > 7 && effectiveEndDate.length() <= 10)
                        {
                            contracts[i].Effective_End_Date__c = Date.valueOf(effectiveEndDate);
                        }
                
			            if(ripList.size() > 0 && ripList[0].Plan_Document_Name__c != null)
			                contracts[i].Plan_Document_Name__c = ripList[0].Plan_Document_Name__c+' '+sources.FirstName__c+' '+sources.LastName__c+' '+dt.month()+'/'+dt.day()+'/'+dt.year();
                        else
                            contracts[i].Plan_Document_Name__c = templateName[0].Name+' '+sources.FirstName__c+' '+sources.LastName__c+' 0'+dt.month()+'/'+dt.day()+'/'+dt.year();
                
                        if(approver.size() > 0)
                        {
                            if(testVar != '' && testVar.length() > 0)
                            {
                                approver[0].Level1__c = Userinfo.getUserId();
                                approver[0].Final_Approver__c = Userinfo.getUserId();
                                approver[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                            }
                                                

                            contracts[i] = populateSalesContractLevels(contracts[i], approver[0], sources.UserID__c);
                        }    
                        if(requiredDate.length() > 7 && requiredDate.length() <= 10)
                        {
                            contracts[i].RequiredReturnDate__c = Date.valueOf(requiredDate);
                        }
                        
                        if(datasource!='True Comp')
                        {
                            contracts[i] = populateNameValuePairs(contracts[i], sources);
                        }
                        else
                        {
                            if(tempDataMap.size() > 0)
                            {   
                                contracts[i] = populateFromTemplateDataMap(contracts[i], tempDataMap[0]);
                            }
                    
                        }
                        
                        contracts[i].AttachmentID__c = attachmentId;
                        planDocumentsList.add(contracts[i]);
                        i++;
                        planDocsCreated++;
                        if(planDocumentsList.size() == 200 || i == src.size())
                        {
                            try
                            {
                                insert planDocumentsList;
                            }
                            catch(DmlException d)
                            {   
                                return 'While inserting Contracts   '+d+'   ';
                            }
                            Integer j=0;
                            String ids = '';
                            planDocumentsList.clear();
                
                        }//end of if(planDocumentsList.size() == 199) 
                        
                    }//end of for(CallidusDataSource__c sources : src)
                
                }//end of for(CallidusDataSource__c[] sources:[SELECT Name,FirstName__c,LastName__c,PayeeID__c,SyncDate__c,UserID__c,UserRoleId__c,UserRoleName__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c FROM CallidusDataSource__c dsc where dsc.UserRoleId__c=:roles.Role_ID__c])
                    
                Batch__c[] btch = [SELECT Status__c,TotalContracts__c,RemainingContracts__c, EndTime__c,Datasource__c from Batch__c b where  b.Id = :BATCHID];
            
                btch[0].RemainingContracts__c = totalDataSources - planDocsCreated;
                btch[0].TotalContracts__c = planDocsCreated;
                btch[0].EndTime__c = datetime.now();
                if(syncDate != null)
                {
                    btch[0].specifydate__c = Date.valueOf(syncDate);
                }
                btch[0].Datasource__c=datasource;
                btch[0].Status__c = 'Completed';
                try
                {
                    update btch;
                    
                }
                catch(DmlException e) 
                {   
                    
                    return 'While updating Batch   ';
                }  
                catch(Exception e)
                {
                    
                    return ''+e;
                }
            
                if(check == 'true')
                    return BATCHID;
                else
                    return 'false';
            }
            catch(Exception e)
            {
                return e.getMessage();
            }   
           
        }                    
        return 'success';
    }//end of defineEligibility2

    WebService static String generateForUsers(String templateId,String batchId, String requiredDate,String datasource)
    {   
        return 'success';
    }

    WebService static String generateForUsers2(String templateId,String batchId, String requiredDate,String datasource, String attachmentId, String effectiveStartDate, String effectiveEndDate)
    {    
        String s = 'success';
        String unSpecificUsers = '';
        String check = 'false';
        SObject scObj = new Sales_Contract__c();
        SObject bObj = new Batch__c();
        DataAccessControlUtil dacu = new DataAccessControlUtil();
        if(dacu.isCreateableObjectByUser(scObj) == 'success' && dacu.isUpdateableObjectByUser(bObj) == 'success')
        {       
            //Get the Approvers assigned for this Template before generation of Plan Documents.
            Approvers__c[] approver = null;
                    
            String[] approverExpectedFields = new String[]{'Template__c','Final_Approver__c','Final_Approver_Date__c','Level1__c','Level2__c','Level3__c','Level4__c','Level5__c','Level6__c','Level7__c','Level8__c','Level9__c','Level10__c','Level11__c','Level12__c','Level13__c','Level14__c','Level15__c','Level1_Due_Date__c','Level2_Due_Date__c','Level3_Due_Date__c','Level4_Due_Date__c','Level5_Due_Date__c','Level6_Due_Date__c','Level7_Due_Date__c','Level8_Due_Date__c','Level9_Due_Date__c','Level10_Due_Date__c','Level11_Due_Date__c','Level12_Due_Date__c','Level13_Due_Date__c','Level14_Due_Date__c','Level15_Due_Date__c'};
            SObject appObj = new Approvers__c();
            Map<String, Schema.SObjectField> approverFieldMap = dacu.getFieldMap(appObj);
            Set<String> allowedROFields = dacu.getAccessibleFields(appObj, approverFieldMap, approverExpectedFields);
            Remote_IP_Address__c[] ripList = [select Is_Global_Approvers_Used__c, Plan_Document_Name__c from Remote_IP_Address__c];
            String formSoql = '';
            if(!allowedROFields.isEmpty())
            {
                formSoql = 'Select ';
                for(String roField: allowedROFields)
                {
                    formSoql += roField+', ';
                }
                formSoql = formSoql.substring(0, formSoql.length() - 2);
                
                //Not filtering using the ownerId as the records are used by all Admins. 
                formSoql += ' from Approvers__c ';
                
                //get Accessible fields for the Where clause filter
                approverExpectedFields = new String[]{'Template__c'};
                allowedROFields = dacu.getAccessibleFields(appObj, approverFieldMap, approverExpectedFields);
                if(!allowedROFields.isEmpty())
                {
                    formSoql += ' where ';
                    for(String roField: allowedROFields)
                    {
                    	if(ripList.size() > 0 && ripList[0].Is_Global_Approvers_Used__c == false)
	                        formSoql += roField+' = :templateId order by CreatedDate desc limit 1 ';
                        else
                        	formSoql += roField+' = null order by CreatedDate desc limit 1 ';
                    }
                    
                }
                approver = Database.query(formSoql);
            }        
        
            URL__c[] url = [SELECT Id, Url_Value__c FROM URL__c];
        
            //Start: Code to check whether all selected users belong to Roles or Titles associated with the Template.
            Template__c[] templateName = [SELECT Id, Name, EligibilityType__c FROM Template__c t where t.Id= :templateId];
            Map<String, String> trMap = new Map<String, String>();
            Map<ID, BatchedUser__c> batchedUserMap = new Map<ID, BatchedUser__c>();

            getUserMap();
            
            if(templateName.size() > 0 && templateName[0].EligibilityType__c == 'Title')
            {
                unSpecificUsers = 'TITLE';
                for(Template_Role__c[] tr : [select User_Title__c from Template_Role__c where Template__c = :templateId])
                {
                    for(Template_Role__c t: tr)
                    {
                        trMap.put(t.User_Title__c, t.User_Title__c);
                    }
                    
                }
                for(BatchedUser__c[] batchedUsers: [SELECT Batchid__c, UserId__c, UserRoleId__c, TemplateId__c, User_Title__c FROM BatchedUser__c bu where bu.Batchid__c = :batchId])
                {
                    for(BatchedUser__c b: batchedUsers)
                    {
                        batchedUserMap.put(b.UserId__c, b);
                        if(trMap.get(b.User_Title__c) == null)
                        {
                            unSpecificUsers += '@'+b.User_Title__c;
                        }
                    }
                    
                }
                if(unSpecificUsers != 'TITLE')
                    return unSpecificUsers;
            }   
            
            if(templateName.size() > 0 && templateName[0].EligibilityType__c == 'Role')
            {
                unSpecificUsers = 'ROLE';
        
                for(Template_Role__c[] tr : [select Role_ID__c from Template_Role__c where Template__c = :templateId])
                {
                    for(Template_Role__c t: tr)
                    {
                        trMap.put(t.Role_ID__c, t.Role_ID__c);
                    }
                }
        
                String bUser = '';
                Map<ID, String> uRoleMap = new Map<ID, String>();
                for(UserRole[] uRoleList : [select Id, Name from UserRole])
                    for(UserRole ur: uRoleList)
                        uRoleMap.put(ur.Id, ur.Name);
                        
                for(BatchedUser__c[] batchedUsers : [SELECT Batchid__c, UserId__c, UserRoleId__c, TemplateId__c,User_Title__c FROM BatchedUser__c bu where bu.Batchid__c = :batchId])
                {
                    for(BatchedUser__c b: batchedUsers)
                    {
                        batchedUserMap.put(b.UserId__c, b);
                    
                        if(trMap.get(b.UserRoleId__c) == null)
                        {
                            unSpecificUsers += '@'+uRoleMap.get(b.UserRoleId__c);
                        }
                    }
                    
                }
                if(unSpecificUsers != 'ROLE')
                    return unSpecificUsers;
            }   
        
            //End: Code to check whether all selected users belong to Roles or Titles associated with the Template.
        
            Batch__c[] batch= null;
            List<Sales_Contract__c> planDocsList = new List<Sales_Contract__c>();
            
            Integer batchednums=0;
        
            batch  = [SELECT Id, Name, BatchID__c, Status__c, StartTime__c, EndTime__c, TotalContracts__c, RemainingContracts__c, TemplateId__c FROM Batch__c bc where bc.Id = :batchId];
            if(batch.size() > 0)
            {
                batch[0].StartTime__c=datetime.now();
                batch[0].Status__c='InProgress';
        
                if(effectiveStartDate.length() > 7 && effectiveStartDate.length() <= 10)
                {
                    batch[0].Effective_Start_Date__c = Date.valueOf(effectiveStartDate);
                }
                
                if(effectiveEndDate.length() > 7 && effectiveEndDate.length() <= 10)
                {
                    batch[0].Effective_End_Date__c = Date.valueOf(effectiveEndDate);
                }
        
        
                try
                {
                    update batch;
                }
                catch(DmlException e)
                {
                    
                    return e.getMessage();
                } 
            }
            
            String str=null;
            Date dt = Date.today();
        
            TemplateDataMap__c[]  tempDataMap = [SELECT Id, Name, TemplateName__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c,Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c FROM TemplateDataMap__c tmap where tmap.TemplateName__c=:templateName[0].Name];
            
            Sales_Contract__c[] contracts= null;
            Integer totContracts = 0;
            Integer planDocsCreated = 0;
            String syncDate = null;
                for(CallidusDataSource__c[] cds : [SELECT Name,FirstName__c,LastName__c,UserID__c,PayeeID__c,SyncDate__c,UserRoleId__c,UserRoleName__c,User_Title__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c, Name31__c, Name32__c, Name33__c, Name34__c, Name35__c, Name36__c, Name37__c, Name38__c, Name39__c, Name40__c, Name41__c, Name42__c, Name43__c, Name44__c, Name45__c, Name46__c, Name47__c, Name48__c, Name49__c, Name50__c, Name51__c, Name52__c, Name53__c, Name54__c, Value31__c, Value32__c, Value33__c, Value34__c, Value35__c, Value36__c, Value37__c, Value38__c, Value39__c, Value40__c, Value41__c, Value42__c, Value43__c, Value44__c, Value45__c, Value46__c, Value47__c, Value48__c, Value49__c, Value50__c, Value51__c, Value52__c, Value53__c, Value54__c,Name55__c,Name56__c,Name57__c,Name58__c,Name59__c,Name60__c,Name61__c,Name62__c,Name63__c,Name64__c,Name65__c,Name66__c,Name67__c,Name68__c,Name69__c,Name70__c,Name71__c,Name72__c,Name73__c,Name74__c,Name75__c,Name76__c,Name77__c,Name78__c,Name79__c,Name80__c,Name81__c,Name82__c,Name83__c,Name84__c,Name85__c,Name86__c,Name87__c,Name88__c,Name89__c,Name90__c,Value55__c,Value56__c,Value57__c,Value58__c,Value59__c,Value60__c,Value61__c,Value62__c,Value63__c,Value64__c,Value65__c,Value66__c,Value67__c,Value68__c,Value69__c,Value70__c,Value71__c,Value72__c,Value73__c,Value74__c,Value75__c,Value76__c,Value77__c,Value78__c,Value79__c,Value80__c,Value81__c,Value82__c,Value83__c,Value84__c,Value85__c,Value86__c,Value87__c,Value88__c,Value89__c,Value90__c FROM CallidusDataSource__c dsc where dsc.UserId__c in : batchedUserMap.keyset()])
                {
                    totContracts += cds.size();
                    contracts = new Sales_Contract__c[cds.size()];
     
                    Integer i=0;
     
                    if(cds.size() == 0)
                    {
                        continue;
                    }
                    if(cds.size()>0)
                    {
    
                        for(CallidusDataSource__c dsc: cds)
                        {
                            if(dsc.PayeeID__c == null && dataSource == 'True Comp')
                                continue;            
    
                            check = 'true';
                            
                            syncDate = dsc.SyncDate__c;
                            
                            contracts[i] = new Sales_Contract__c();
                
                            contracts[i].FirstName__c=dsc.FirstName__c;
                
                            contracts[i].LastName__c =dsc.LastName__c;
                            contracts[i].UserRoleId__c = dsc.UserRoleId__c;
                            
                            contracts[i].UserID__c=dsc.UserID__c; 
                            contracts[i].User_ID__c= dsc.UserID__c;
    
                            contracts[i].PayeeID__c=dsc.PayeeID__c;
                            contracts[i].UserRoleName__c=dsc.UserRoleName__c;
                            contracts[i].User_Title__c=dsc.User_Title__c;
                            
                            contracts[i].Generated_Date__c= dt;
                            contracts[i].Status__c= 'Draft';
                            contracts[i].isWSCall__c = false;
                            contracts[i].BatchID__c = batchId;
                            contracts[i].Batch__c = batchId;                         
                            contracts[i].TemplateName__c = templateName[0].Name;
                            contracts[i].Template__c = templateName[0].Id;
    
                            if(url.size() > 0)
                            {
                                contracts[i].Url__c=url[0].Url_Value__c;
                            }
    
                            if(effectiveStartDate.length() > 7 && effectiveStartDate.length() <= 10)
                            {
                                contracts[i].Effective_Start_Date__c = Date.valueOf(effectiveStartDate);
                            }
                            
                            if(effectiveEndDate.length() > 7 && effectiveEndDate.length() <= 10)
                            {
                                contracts[i].Effective_End_Date__c = Date.valueOf(effectiveEndDate);
                            }
         
				            if(ripList.size() > 0 && ripList[0].Plan_Document_Name__c != null)
                                contracts[i].Plan_Document_Name__c = ripList[0].Plan_Document_Name__c+' '+dsc.FirstName__c+' '+dsc.LastName__c+' '+dt.month()+'/'+dt.day()+'/'+dt.year();
                            else
                                contracts[i].Plan_Document_Name__c = templateName[0].Name+' '+dsc.FirstName__c+' '+dsc.LastName__c+' 0'+dt.month()+'/'+dt.day()+'/'+dt.year();
    
                            if(approver.size() > 0)
                            {
                                if(testVar != '' && testVar.length() > 0)
                                {
                                    approver[0].Level1__c = Userinfo.getUserId();
                                    approver[0].Final_Approver__c = Userinfo.getUserId();
                                    approver[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                                }
                                                
                                contracts[i] = populateSalesContractLevels(contracts[i], approver[0], dsc.UserID__c);
                            }    
                            if(requiredDate.length() > 7 && requiredDate.length() <= 10)
                            {
                                contracts[i].RequiredReturnDate__c = Date.valueOf(requiredDate);
                            }
                
                            if(datasource!='True Comp')
                            {
                                contracts[i] = populateNameValuePairs(contracts[i], dsc);
                            }
                            else
                            {    
                                contracts[i] = populateFromTemplateDataMap(contracts[i], tempDataMap[0]);
                            }      
                            contracts[i].AttachmentID__c = attachmentId;
                            planDocsList.add(contracts[i]);
                            i++;
                            planDocsCreated++;
                            if(planDocsList.size() == 200)
                            {
                                try
                                {
                                    insert planDocsList;
                                }
                                catch(DmlException d)
                                {   
                                    return s+' IN CONTRACTS    '+d;
                                }
                                planDocsList.clear();
                    
                            }//end of if(planDocsList.size() == 200)
                        }//end of for(CallidusDataSource dsc : cds)
                    }//end of if(cds.size() > 0)
                }//end of for(CallidusDataSource__c[] cds : [SELECT Name,FirstName__c,LastName__c,UserID__c,PayeeID__c,SyncDate__c,UserRoleId__c,UserRoleName__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c FROM CallidusDataSource__c dsc where dsc.UserId__c=:users.UserId__c])
            
            if(planDocsList.size() > 0)
            {
                try
                {
                    insert planDocsList;
                }
                catch(DmlException d)
                {   
                    return s;
                }
                planDocsList.clear();
        
            }//end of if(planDocsList.size() > 0)
        
            
            if(batch.size() > 0)
            {
                Batch__c[] btch = [SELECT  TemplateId__c,specifydate__c, Status__c, EndTime__c, TotalContracts__c, RemainingContracts__c,Datasource__c from Batch__c b where b.Id = :batch[0].Id];
                if(btch.size() > 0)
                {
                    btch[0].EndTime__c = datetime.now();
                    btch[0].Status__c = 'Completed';
                    btch[0].TemplateId__c = templateId;
                    if(syncDate != null)
                    {
                        btch[0].specifydate__c = Date.valueOf(syncDate);
                    }
                    btch[0].Datasource__c = datasource;
                    
                    btch[0].TotalContracts__c = planDocsCreated;
                    
                    btch[0].RemainingContracts__c = totContracts - btch[0].TotalContracts__c;
                    try
                    {
                        update btch;
                    }
                    catch(DmlException e)
                    {
                    
                    } 
                }
            }//end of if(batch.size() > 0)
        }       
        return check;//'success';
    
    }

    WebService static String[] getTemplateAttachments(String templateId)
    {
        Schema.DescribeSobjectResult dsr = Attachment.sObjectType.getDescribe();
        Schema.DescribeFieldResult dfrId = Attachment.Id.getDescribe();
        Schema.DescribeFieldResult dfrName = Attachment.Name.getDescribe();
        Schema.DescribeFieldResult dfrBody = Attachment.Body.getDescribe();
        Schema.DescribeFieldResult dfrContentType = Attachment.ContentType.getDescribe();
        Schema.DescribeFieldResult dfrPId = Attachment.Parent.Id.getDescribe();
        
        String[] attachmentsList = new List<String>();
        
        if(dsr.isAccessible() && dfrId.isAccessible() && dfrName.isAccessible() && dfrBody.isAccessible() && dfrContentType.isAccessible() && dfrPId.isAccessible())
        {
    
            Attachment[] a = [select Id, Name, Body, ContentType from Attachment a where a.ParentId = :templateId];
            
            if(a.size() > 0)
            {
                String body = '';
                for(Integer i=0;i<a.size();i++)
                {
                    body = a[i].Body.toString();
                    Integer indexOfBody = body.indexOf('<body', 0);
                    if(indexOfBody == -1)
                        indexOfBody = body.indexOf('<Body', 0);
        
                    if(indexOfBody == -1)
                        indexOfBody = body.indexOf('<BODY', 0);
                    
                    String extractedBody = '';
                    if(indexOfBody != -1)
                    {
                        extractedBody = body.substring(indexOfBody);
                    
                        Integer indexOfLFB = extractedBody.indexOf('{', 0);
                        Integer indexOfRFB = extractedBody.indexOf('}', 0);
                        
                        if(indexOfLFB != -1 && indexOfRFB != -1)
                        {
                            attachmentsList.add(a[i].Id);
                            attachmentsList.add(a[i].Name);
                        }
                    }
                }//end of for
            }//end of if(a.size())
        }
        return attachmentsList;
    }//end of getTemplateAttachments()
    

    WebService static String updateBatch(String batchId, String BatchName, String templateId, String SpecifyInDate, String RequiredDate, String url, String customButtonId)
    {
        SObject scObj = new Batch__c();
        DataAccessControlUtil dacu = new DataAccessControlUtil();
        if(dacu.isUpdateableObjectByUser(scObj) == 'success')
        {       
            Batch__c[]  batch = [SELECT Id, Name, BatchID__c, Status__c, StartTime__c,EndTime__c, TotalContracts__c, RemainingContracts__c, Template__c, TemplateId__c, Owner.Id, Owner.Email FROM Batch__c bc where bc.Id = :batchId];
            if(batch.size() == 0)
            {
             return 'Batch does not exist';
            }
            String str = '';
            if(batch.size() > 0)
            { 
                batch[0].Name = BatchName;
                batch[0].Template__c = templateId;
                if(SpecifyInDate.length() > 7 && SpecifyInDate.length() <= 10 )
                {
                    batch[0].specifydate__c = Date.valueOf(SpecifyInDate);
                }
                if(RequiredDate.length() > 7 && RequiredDate.length() <= 10)
                {
                    batch[0].RequiredReturnDate__c = Date.valueOf(RequiredDate);
                }
                
                try
                {
                    update batch;
                }
                catch(DmlException e) 
                { 
                    return e.getMessage();
                }
                
                String subject = 'Plan Document generation has completed for the Batch '+BatchName+'.';
                String textBody = 'Plan Document generation has been Generated.';
                String htmlBody = 'Plan Document Generation Completed for the Batch '+BatchName+'.<br/><a href="'+url+''+templateId+'">Click here</a> to view the Template used to create the batch.<br/><a href="'+url+'servlet/servlet.Integration?scontrolCaching=1&lid='+customButtonId+'&eid='+templateId+'&ic=1&rSel=all&bcId='+batchId+'">Click here</a> to view the Batch created.  ';
                
                //Send mail to Admin with a link to the contract.
                try
                {
                    str = sendMailToUser(batch[0].Owner.Id, subject, textBody, htmlBody);
                }
                catch(Exception e)
                {
                    return e.getMessage();
                }
            }//end of if(batch.size() > 0)
            
            Sales_Contract__c[] sc = [select Id, Name, BatchName__c, Status__c, BatchID__c from Sales_Contract__c s where s.BatchID__c = :batchId];
            if(sc.size() > 0)
            {
                for(Integer p=0; p<sc.size(); p++)
                {
                    sc[p].BatchName__c = BatchName;
        
                    if(testVar != '' && testVar.length() > 0)
                    {
                        sc[0].Level1__c = UserInfo.getUserId();
                        sc[0].Final_Approver__c = UserInfo.getUserId();
                        sc[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                    }
            
                    if(testVar == 'Published')
                    {
                        sc[0].Status__c = 'Published';
                    }
                    if(testVar == 'Plan Approved 1')
                        sc[0].Status__c = 'Plan Approved by Engineering Callidus';
                    if(testVar == 'Plan Rejected 1')
                        sc[0].Status__c = 'Plan Rejected by Engineering Callidus';
            
                }
                
                try
                {
                   update sc; 
                }
                catch(Exception e)
                {
                    return e.getMessage();
                }
            }
        }           
        return 'success';
    }
    
    WebService static String updatePlanDocStatus(String[] salesContractId, String batchId, String url, String requiredReturnDate)
    {
        return 'success';
    }
    

    WebService static String getCurrentDateTime(String time1)
    {
        Datetime dt = Datetime.now();
        dt.format('MM/dd/yyyy hh:mm:ss a');
        return ' '+dt.format('MM/dd/yyyy hh:mm:ss a');
    }

    WebService static String shareRecordToUser(String contractId, String userId)
    {
          Sales_Contract__Share scShare  = new Sales_Contract__Share();
          
          scShare.ParentId = contractId;
          
          // Set the ID of user or group being granted access.
          scShare.UserOrGroupId = userId;
          
          
          // Set the access level.
          scShare.AccessLevel = 'Edit';
          
          scShare.RowCause = Schema.Sales_Contract__Share.RowCause.Manual;
          
          Database.SaveResult sr = Database.insert(scShare,false);
    
          if(!sr.isSuccess())
          {
            Database.Error err = sr.getErrors()[0];
            if(err.getStatusCode() == StatusCode.FIELD_INTEGRITY_EXCEPTION  && err.getMessage().contains('AccessLevel'))
            {
              return 'Success in IF'+err;
            }
            else
            {
              return 'Failure';
            }
          }
          else
          {
             return 'Success in Else';   
          }
          return 'success';
    }
    
}